import type { ItemResult } from "@/types/search";

const forbidArr = ["link"]
// const pagefind = await import('/pagefind/pagefind.js')

function isLongestIncreasingSubsequence(str1: string, str2: string) {
  let i = 0, j = 0;
  while (i < str1.length && j < str2.length) {
    if (str1[i] === str2[j]) {
      i++;
    }
    j++;
  }
  return i === str1.length;
}

function getResult(keyword: string, str: string) {
  const len = keyword.length
  if (len < 4) {
    return str.includes(keyword)
  }
  else {
    return isLongestIncreasingSubsequence(keyword, str)
  }
}

export function search(keyword: string, Result: ItemResult[], custonForbid?: string[]) {
  const FinalForbid = custonForbid ?? forbidArr
  const hits: ItemResult[] = []
  for (const i of Result) {
    for (const j of Object.entries(i)) {
      if (!FinalForbid.includes(j[0]) && typeof j[1] == "string" && getResult(keyword, j[1].toLowerCase())) {
        hits.push(i)
        break
      }
    }
  }
  return hits
}